<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/2/12
 * Time: 16:06
 */

namespace Kordar\Tree;

class Forest implements ForestInterface
{
    private $groups;

    public function __construct($groups)
    {
        $this->groups = $groups;
    }

    public function output($rootKey = 0)
    {
        // TODO: Implement output() method.
        $forest = [];

        if (isset($this->groupHeap[$rootKey])) {
            $rootNodes = $this->groups[$rootKey];
            $forest = $this->generateTree($rootNodes, 0);
        }

        return $forest;
    }

    // 生成树
    protected function generateTree($levelsNode, $depth)
    {
        $root = [];
        foreach ($levelsNode as $key => $node) {
            $nodeId = $node->data['id'];

            $children = [];
            if (isset($this->groupHeap[$nodeId])) {
                $t = $this->groups[$nodeId];
                $children = $this->generateTree($t, $depth++);
            }

            /*if (empty($node['href']) && empty($children)) {
                continue;
            }*/

            $root[$key] = $node->data;
            $root[$key]['children'] = $children;
        }
        return $root;
    }
}